var MongoClient = require('mongodb').MongoClient
var assert = require('assert')
var fs=require('fs')
var path=require('path')
var BSON=require('bson')
var dbUrl='mongodb://localhost:27017/dataSpace'
const collectionName="users"
var dataSpaceDB

MongoClient.connect(dbUrl,function(err,db){
    if (err) throw err
    console.log('数据库已创建')
    dataSpaceDB=db.db("dataspace")
    createCollection()
})

var createCollection=()=>{
    dataSpaceDB.createCollection(collectionName,function(err,res){
        if(err) throw err
        console.log("创建集合")
    })
    var userJson=JSON.parse(fs.readFileSync(path.join(__dirname,"../public/data/userSample.json")))
    dataSpaceDB.collection(collectionName).countDocuments({},(err,count)=>{
        if (count===0){
            dataSpaceDB.collection(collectionName).insertOne(userJson,(err,result)=>{
                if (err) throw err;
                console.log("用户模板插入成功");
            })
        }
    })
}

var find=(selector,needresult,returnRes)=>{
    var col = dataSpaceDB.collection(collectionName)
    if(needresult==null) needresult=undefined
    col.find(selector).project(needresult).toArray(function(err,result){
        try{
            assert.equal(err,null)
        }
        catch(e){
            console.log(e)
            result=[]
        }
        returnRes(result)
    })

}
var add=(selector,returnRes)=>{
    var col=dataSpaceDB.collection(collectionName)
    col.insertMany([selector],(err,result)=>{
        try{
            assert.equal(err,null)
        }
        catch(e){
            console.log(e)
            result=[]
        }
        returnRes(result)
    })
}
var deletes=(selector,returnRes)=>{
    var col=dataSpaceDB.collection(collectionName)
    col.deleteOne(selector,(err,result)=>{
        try{
            assert.equal(err,null);
            assert.notStrictEqual(0,result.result.n)
        }
        catch(e){
          console.log(e)
          result.result = ""
        }
        returnRes(result.result ? [result.result] : [])
    })
}
var updates=(selector,returnRes)=>{
    var col=dataSpaceDB.collection(collectionName)
    col.updateOne(whereStr, updateStr,(err,result)=>{
        try{
            assert.equal(err,null)
            assert.notStrictEqual(0,result.result.n)
        }
        catch(e){
            console.log(e)
            result.result=""
        }
        returnRes(result.result ? [result.result] : []) //如果没报错且返回数据不是0，那么表示操作成功。
    })
}

exports.createCollection=createCollection
exports.find=find
exports.add=add
exports.deletes=deletes
exports.updates=updates
